<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Config;
use think\Db;
use think\Validate;
use think\Session;
use fast\WechatMini;
use addons\third\model\Third;
use think\Log;
use think\Request;
use fast\Http;
use think\Exception;
use addons\third\library\Service;

/**
 * 首页接口
 */
class Hall extends Api
{
    protected $noNeedLogin = ['login','getconfig','getMendian1','token','loginacc','loginacc2'];
    protected $noNeedRight = ['*'];


    public function _initialize()
    {
        $this->token = $this->request->post('token');

        parent::_initialize();

    } 

    /**
     * 会员登录
     *
     * @ApiMethod (POST)
     * @param string $account  账号
     * @param string $password 密码
     */


     public function updateMobile(){
        $post = $this->request->request();
        $third = Third::where(['user_id' =>$this->auth->id])->find();
        if (empty($third)) {
            $this->error('用户不存在');
        }


        $wechat = new WechatMini();

        $res = $wechat->getuserphonenumber($post['code']);



        if ($res['errcode'] == 0) {
            $map['id'] = $this->auth->id;
            $update['mobile'] = $res['phone_info']['phoneNumber'];
            Db::table('fa_user')->where($map)->update($update);

            $data = $this->getUserInfo();
            $data['mobile'] = $update['mobile'];

            $this->success("成功",['userInfo' => $data]);
        }else{
            $this->error('失败');
        }

  
    }
    
    public function updateUser(){
        $post = $this->request->request();   
            
        if (empty($post['avata'])) {
            $this->error('请上传头像');
        }

        if (empty($post['nickname'])) {
            $this->error('请输入昵称');
        }
        
        $map['id'] = $this->auth->id;
        $updata['nickname'] = $post['nickname'];
        $updata['avatar'] = $post['avata'];
        $updata['up_status'] = 1;
        Db::table('fa_user')->where($map)->update($updata);

        $this->success("成功");
    }
    
    

    public function login()
    {
        $post = $this->request->request();  

        if ($post['chose'] == 'false') {
            $this->error("请同意用户协议");
        }
         
        Log::error('注册账号'.json_encode($post));
        $code = $this->request->post("code");
        $post_uid = $this->request->post("uid");
        $rawData = $this->request->post("rawData", '', 'trim');
        if (!$code || !$rawData) {
            $this->error("参数不正确");
        }
        $userInfo = (array)json_decode($rawData, true);
        $config = get_addon_config('third');
        $params = [
            'appid'      => $config['wechat_mini']['app_id'],
            'secret'     => $config['wechat_mini']['app_secret'],
            'js_code'    => $code,
            'grant_type' => 'authorization_code'
        ];


        $wechat = new WechatMini();

        $res = $wechat->getuserphonenumber($post['mobilecode']);

        $mobile = '';

        if ($res['errcode'] == 0) {
            $mobile = $res['phone_info']['phoneNumber'];
        }else{
            logs('weixin_register',json_encode($res,JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
            $this->error("获取手机号失败");
        }


        $result = Http::sendRequest("https://api.weixin.qq.com/sns/jscode2session", $params, 'GET');
        if ($result['ret']) {
            $json = (array)json_decode($result['msg'], true);
            if (isset($json['openid'])) {
                if ($this->token) {
                    $this->auth->init($this->token);
                    //检测是否登录
                    if ($this->auth->isLogin()) {
                        $third = Third::where(['openid' => $json['openid'], 'platform' => 'wechat'])->find();
                        if ($third && $third['user_id'] == $this->auth->id) {


                            $map_user['id'] = $this->auth->id;
                            $updata['mobile'] = $mobile;
                            Db::table('fa_user')->where($map_user)->update($updata);

                            $this->success("登录成功", ['userInfo' => $this->getUserInfo()]);
                        }
                    }
                }
                $platform = 'wechat';
                $result = [
                    'openid'        => $json['openid'],
                    'userinfo'      => [
                        'nickname' => $mobile,
                    ],
                    'access_token'  => $json['session_key'],
                    'refresh_token' => '',
                    'expires_in'    => isset($json['expires_in']) ? $json['expires_in'] : 0,
                    'apptype'       => 'miniapp'
                ];
                $extend = ['gender' => 0, 'nickname' => $mobile, 'avatar' => ''];
                $uid = 0;
                if (!empty($post_uid)) {
                    $uid = $post_uid;
                }
                $extend['parent_user_id'] = $uid;
                $extend['mobile'] = $mobile;
                $ret = Service::connect($platform, $result, $extend,0);
                if ($ret) {

                    $this->success("登录成功", ['userInfo' => $this->getUserInfo()]);
                } else {
                    $this->error("连接失败");
                }
            } else {
                $this->error("登录失败");
            }

        }
        return;

    }

    /**

     * 获取配置

     */

    public function getconfig()

    {

       $site = Config::get("site");

       $this->success("登录成功", $site);

    }


        /**
     * 会员登录
     *
     * @ApiMethod (POST)
     * @param string $account  账号
     * @param string $code 密码
     */
    public function Token()
    {
        $post = $this->request->request();    
        $id = $this->request->request('user_id');
        $token = $this->request->request('token');
        if (empty($id)) {
            $this->error(__('登录失效1'));
        }
        
        // $user = \app\common\model\User::getById($id);
        // // var_dump($user)
      
        // if ($user) {

        //     // var_dump($user->token);
        //     // if ($user->token != $token) {
        //     //     $this->error(__('登录失效3'));
        //     // }
        //     //如果已经有账号则直接登录
        //     $ret = $this->auth->direct($user->id);
        //     $data = ['userinfo' => $this->getUserinfo()];
        //     $this->success(__('登录成功'), $data);
        // }else{
        //     $this->error('失败');
        // } 


        if (empty($token)) {
            $this->error(__('登录失效2'));
        }

        if ($this->token) {
            $this->auth->init($this->token);
                    //检测是否登录
            if ($this->auth->isLogin()) {
                  $this->success("登录成功", ['userinfo' => $this->getUserInfo()]);
            }
        }else{
            $this->error('失败');
        } 
        
        

    }
    
    
    
    /**
     * 会员登录
     *
     * @ApiMethod (POST)
     * @param string $account  账号
     * @param string $password 密码
     */
    public function loginacc()
    {   

        $post = $this->request->request();  

        if ($post['chose'] == 'false') {
            $this->error("请同意用户协议");
        }
       
        $account = $this->request->post('account');
        $password = $this->request->post('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = ['userinfo' => $this->getUserinfo()];
            $this->success(__('登录成功'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 会员登录
     *
     * @ApiMethod (POST)
     * @param string $account  账号
     * @param string $password 密码
     */
    public function loginacc2()
    {   

        $post = $this->request->request();  

        if ($post['chose'] == 'false') {
            $this->error("请同意用户协议");
        }
       
        $account = $this->request->post('account');
        $password = $this->request->post('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = ['userinfo' => $this->getUserinfo()];
            
            if ($data['userinfo']['group_id'] != 4) {
               $this->error('您好，您不是配送员无法登录');
            }
            $this->success(__('登录成功'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }




  
     protected function getUserInfo()

    {   


        $allowFields = ['id', 'username', 'nickname', 'mobile', 'avatar', 'score','money','token','shouyi','birthday','gender','up_status','money','group_id','inv_id','code','renzheng','free_vip'];
        $this->auth->setAllowFields($allowFields);

        $userinfo = $this->auth->getUserInfo();
        
        if (empty($userinfo['code'])) {
           $image = getcode($this->auth->id,'/pages/index/index?xiaoshou='.$this->auth->id);

           $map1['id'] = $this->auth->id;
           $updat1['code'] = $image;
           Db::table('fa_user')->where($map1)->update($updat1);

 
           $userinfo = $this->auth->getUserInfo();
        }

        $userinfo['avatar'] = cdnurl($userinfo['avatar'], true);
        
      

        $group = Db::table('fa_user_group')->find($userinfo['group_id']);
      
        


        $vip = get_addon_info('vip');
        $userinfo['group_name'] = $group['name'];
        $userinfo['is_install_vip'] = ($vip && $vip['state']);
        $userinfo['code'] = $this->request->root(true).$userinfo['code'];    
        if (!$userinfo['is_install_vip']) {//禁用

            $userinfo['vip'] = 0;

            $userinfo['vipInfo'] = null;

        } else {

            $userinfo['vipInfo'] = \addons\vip\library\Service::getVipInfo($userinfo['id']) ?? null;

            if (empty($userinfo['vipInfo'])) {

                $userinfo['vip'] = 0;

            }

        }
        return $userinfo;

    }
}
